<template>
    <div class="map-wrapper" id="dis">
        <div id="container"></div>
        <div class="search-container">
            <input
                class="search-input"
                v-model="locationInfo"
                placeholder="正在获取位置..."
                readonly
            />
        </div>
        <div class="button-group">
            <button class="locate-btn" @click="getCurrentLocation">重新定位</button>
        </div>

        <div>
        <el-button type="text" @click="signIn"> 确认打卡</el-button>
        </div>
    </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
    securityJsCode: '43b49967b8f1c20b8eda3a89559d4ced'
}

export default {
    data() {
        return {
            map: null,
            locationInfo: '',
            geolocation: null,
            marker: null,
            geocoder: null
        }
    },
    mounted() {
        this.initMap()
    },
    methods: {
      signIn(){

        this.$http.post('/tAssign/signIn',{
           address: this.locationInfo
        })
          .then(response => {
            console.log(response);
            alert("签到成功")
          })
          .catch(error => {
            console.error(error);
          });


      },


        initMap() {
            AMapLoader.load({
                key: "45d923614ae9263b5641d7b0139c510c",
                version: "2.0",
                plugins: [
                    'AMap.Geolocation',
                    'AMap.Geocoder'
                ],
            }).then((AMap) => {
                this.map = new AMap.Map("container", {
                    viewMode: "3D",
                    zoom: 17, // 增加默认缩放级别以显示更多细节
                    center: [116.397428, 39.90923],
                });

                // 初始化定位插件
                this.geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, // 启用高精度定位
                    timeout: 10000,
                    convert: true,
                    showButton: false,
                    showMarker: true,
                    showCircle: true,
                    panToLocation: true,
                    zoomToAccuracy: true
                });

                // 初始化地理编码插件
                this.geocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                });

                this.map.addControl(this.geolocation);

                // 自动定位
                this.getCurrentLocation();

            }).catch(e => {
                console.error('地图加载错误：', e);
                this.locationInfo = '地图加载失败';
            });
        },

        getCurrentLocation() {
            if (!this.map) return;
            this.locationInfo = "正在获取位置...";

            this.geolocation.getCurrentPosition((status, result) => {
                if (status === 'complete') {
                    const position = result.position;
                    this.getDetailAddress(position);
                } else {
                    console.log('浏览器定位失败，尝试IP定位');
                    this.fallbackToIPLocation();
                }
            });
        },

        getDetailAddress(position) {
            this.geocoder.getAddress([position.lng, position.lat], (status, result) => {
                if (status === 'complete' && result.regeocode) {
                    const address = result.regeocode;
                    // 组合详细地址
                    this.locationInfo = this.formatAddress(address);

                    // 更新地图视图
                    this.map.setCenter([position.lng, position.lat]);
                    this.map.setZoom(17);

                    // 更新标记
                    if (this.marker) {
                        this.marker.setMap(null);
                    }
                    this.marker = new AMap.Marker({
                        position: [position.lng, position.lat],
                        map: this.map
                    });
                }
            });
        },

        formatAddress(address) {
            const addressComponent = address.addressComponent;
            const building = address.aois && address.aois.length > 0 ?
                address.aois[0].name : '';

            let detailAddress = [
                addressComponent.province,
                addressComponent.city,
                addressComponent.district,
                addressComponent.township,
                addressComponent.street,
                addressComponent.streetNumber,
                building
            ].filter(Boolean).join('');

            // 如果有POI信息，添加到地址中
            if (address.pois && address.pois.length > 0) {
                detailAddress += ` (附近：${address.pois[0].name})`;
            }

            return detailAddress;
        },

        fallbackToIPLocation() {
            const citySearch = new AMap.CitySearch();
            citySearch.getLocalCity((status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                    const citylocation = result.rectangle.split(';')[0].split(',');

                    this.map.setCenter(citylocation);
                    this.locationInfo = `${result.province}${result.city}`;

                    if (this.marker) {
                        this.marker.setMap(null);
                    }
                    this.marker = new AMap.Marker({
                        position: citylocation,
                        map: this.map
                    });

                    // 获取更详细的地址信息
                    this.getDetailAddress({
                        lng: parseFloat(citylocation[0]),
                        lat: parseFloat(citylocation[1])
                    });
                } else {
                    this.locationInfo = '无法获取位置信息';
                }
            });
        }
    }
}
</script>

<style scoped>
.map-wrapper {
    position: relative;
    width: 800px;
    height: 600px;
    /* margin-left: 240px; */
}

#container {
    width: 100%;
    height: 100%;
}

.search-container {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 999;
    width: 400px; /* 增加宽度以显示更多信息 */
}

.search-input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 14px;
    background: rgba(255, 255, 255, 0.95);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.button-group {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 999;
}

.locate-btn {
    padding: 8px 15px;
    background: #409EFF;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.locate-btn:hover {
    background: #66b1ff;
}

.locate-btn:active {
    background: #3a8ee6;
}

.search-input:focus {
    outline: none;
    border-color: #409EFF;
    box-shadow: 0 2px 6px rgba(64,158,255,0.2);
}
</style>
